import datetime
import sqlite3

from sam import operate_record_db


class sqlLiteUtil(object):

    def __init__(self):
        super().__init__()
        self.db = sqlite3.connect(operate_record_db)
        self.cursor = self.db.cursor()
        self.create_table()

    def __del__(self):
        if self.cursor:
            self.cursor.close()
        if self.db:
            self.db.close()

    def create_table(self):
        create_table_sql = """
            CREATE TABLE IF NOT EXISTS 
            import_yb_original_lx_data_record 
            ( 
            operate_source_name text
            , operate_time datetime
            , operator text 
            )       
        """
        self.cursor.execute(create_table_sql)
        self.db.commit()

    def assert_record_is_exist(self, operate: str):
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        check_sql = f"select * from import_yb_original_lx_data_record" \
                    f" where operate_source_name = '{operate}' and operate_time = '{today}' "
        self.cursor.execute(check_sql)
        record = self.cursor.fetchall()
        return True if record else False

    def insert_record(self, operate: str):
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        insert_sql = f" insert into import_yb_original_lx_data_record (operate_source_name, operate_time, operator) " \
                     f"values ('{operate}', '{today}', 'sam')"
        self.cursor.execute(insert_sql)
        self.db.commit()

    def delete_record(self, operate: str):
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        delete_sql = f"delete from import_yb_original_lx_data_record " \
                     f"where operate_source_name = '{operate}' and operate_time = '{today}' "
        self.cursor.execute(delete_sql)
        self.db.commit()


sql_lite_util = sqlLiteUtil()


def check_exists_import_operate_record(operate_source_name: str) -> bool:
    return sql_lite_util.assert_record_is_exist(operate_source_name)


def insert_import_operate_record(operate_source_name: str):
    sql_lite_util.insert_record(operate_source_name)


def delete_import_operate_record(operate_source_name: str):
    sql_lite_util.delete_record(operate_source_name)
